/*
 * File:        uart.c
 * Purpose:     Provide UART routines for serial IO
 *
 * Notes:
 *
 */

#include "derivative.h"
#include "uart.h"

/********************************************************************/
/*
 * Initialize the UART for 8N1 operation, 115200 Baud rate, interrupts
 * disabled, and no hardware flow-control
 *
 * System Clock is 50 MHz
 *
 */
void uart_init ()
{
	/* Enable clock for UART5 */
	SIM_SCGC1 |= SIM_SCGC1_UART5_MASK;
	/* Disable Tx and Rx for now... */
	UART5_C2 &= ~0x0c;
	
	/* Init baud rate. */
	UART5_BDH = 0x00;
	UART5_BDL = 0x1b;
	
	/* Set flags in UART3_C1 */
	UART5_C1 = 0x0;
	
	/* Set fine adjust to compensate for integer arithmetic error. */
	UART5_C4 = 0x4; /* Fine adjust = .125 */
	
	/* Enable Tx and Rx */
	UART5_C2 = 0x0c;
}

/********************************************************************/
/*
 * Wait for a character to be received on the specified UART
 *
 *
 * Return Values:
 *  the received character
 */
char uart_getchar ()
{
	 /* Wait until character has been received */
	    while (!(UART_S1_REG(UART5_BASE_PTR) & UART_S1_RDRF_MASK));
	    
	    /* Return the 8-bit data from the receiver */
	    return UART_D_REG(UART5_BASE_PTR);
}

/********************************************************************/
/*
 * Wait for space in the UART Tx FIFO and then send a character
 *
 * Parameters:
 *  ch			 character to send
 */
void uart_putchar (char ch)
{
    /* Wait until space is available in the FIFO */
    while(!(UART_S1_REG(UART5_BASE_PTR) & UART_S1_TDRE_MASK));
    
    /* Send the character */
    UART_D_REG(UART5_BASE_PTR) = (int)ch;
}

/********************************************************************/
/*
 * Check to see if a character has been received
 *
 * Parameters:
 *  channel      UART channel to check for a character
 *
 * Return values:
 *  0       No character received
 *  1       Character has been received
 */
int uart_getchar_present ()
{
	 return (UART_S1_REG(UART5_BASE_PTR) & UART_S1_RDRF_MASK);
}
/********************************************************************/

